/*
 * @Author: shanghongyun 2879455630@qq.com
 * @Date: 2025-05-30 13:17:18
 * @LastEditors: shanghongyun 2879455630@qq.com
 * @LastEditTime: 2025-06-10 15:36:39
 * @FilePath: \A05\Dev\ADC.c
 * @Description: ADC配置文件
 */

#include "dev.h"
#include "charger.h"


void delay_us(uint32_t us){
    uint32_t cnt = us * 12;   /*48Mhz*/
    while(cnt--){
        ;
    }
}



/**
 * @description: eadc配置
 * @return {*}
 */
void eadc_config(void){

    uint32_t temp1 = 0 , temp2 = 0;
    // Set EADC clock source to HIRC 12mhz
    CLK_SetModuleClock(EADC_MODULE, CLK_EADC_SRC_HIRC, CLK_CLKDIV_EADC(4));

	// Reset IP
    SYS_ResetModule(EADC_RST);
      
    //管脚配置 PB      
    SYS->GPB_MFP |= SYS_GPB_MFP_PB0_ADC0_CH0 | SYS_GPB_MFP_PB1_ADC0_CH1 | SYS_GPB_MFP_PB2_ADC0_CH2 | SYS_GPB_MFP_PB4_ADC1_CH0;
    GPIO_SetMode(PB, BIT0 | BIT1 | BIT2 | BIT4, GPIO_MODE_INPUT);
    GPIO_DISABLE_DIGITAL_PATH(PB, BIT0 | BIT1 | BIT2 | BIT4);

    //PC
    SYS->GPB_MFP |= SYS_GPC_MFP_PC0_ADC0_CH3 | SYS_GPC_MFP_PC1_ADC0_CH4 | SYS_GPC_MFP_PC2_ADC1_CH2;
    GPIO_SetMode(PC, BIT0 | BIT1 | BIT2, GPIO_MODE_INPUT);
    GPIO_DISABLE_DIGITAL_PATH(PC, BIT0 | BIT1 | BIT2);

    //电流偏置读取
    EADC_Open(EADC, NULL);
    delay_us(5);
    EADC_SET_SIMULTANEOUS_SIMPLE_MODE(EADC);//同时采样模式
    EADC_SetExtendSampleTime(EADC, NULL, 5);

    EADC_DISABLE_INT(EADC,EADC_CTL_ADC0IEN_Msk);//禁止ADC中断
    EADC_CLR_INT_FLAG(EADC, EADC_STATUS_ADC0F_Msk);
    EADC->CTL &= ~EADC_CTL_ADC0HWTRGEN_Msk;//硬件触发禁止
    
    EADC->CTL = (EADC->CTL & (~EADC_CTL_ADC1CHSEL_Msk)) | ADC1_CUR_L_Channel;
    EADC->CTL = (EADC->CTL & (~EADC_CTL_ADC0CHSEL_Msk)) | ADC0_CUR_R_Channel;
    EADC_CLR_INT_FLAG(EADC, EADC_STATUS_ADC0F_Msk);
    
    for(int i = 0; i < 16; i++)
    {
        EADC_START_CONV(EADC, EADC_CTL_ADC0SWTRG_Msk);              // software trigger EADC0
        while (!EADC_GET_INT_FLAG(EADC, EADC_STATUS_ADC0F_Msk));    // wait EADC0 completed by polling,ADC转换不成功

        EADC_CLR_INT_FLAG(EADC, EADC_STATUS_ADC0F_Msk);
        
        temp1 +=((EADC->DAT[0] & EADC_DAT0_ADC1DAT0_Msk) >> EADC_DAT0_ADC1DAT0_Pos);	//母线电流
        temp2 +=((EADC->DAT[0] & EADC_DAT0_ADC0DAT0_Msk) >> EADC_DAT0_ADC0DAT0_Pos);	//SPEED
      
    }
    charger.battery_L.current_offset = temp1 >> 4;	//充电电流偏移
    charger.battery_R.current_offset = temp2 >> 4;	//充电电流偏移

    EADC_Close(EADC);
		
    delay_us(5);

    EADC_Open(EADC, NULL);
    EADC_SET_SIMULTANEOUS_SIMPLE_MODE(EADC);//同时采样模式
    // Configure EADC sample time to 6 EADC clocks
    EADC_SetExtendSampleTime(EADC, NULL, 5);
	
    
	gEADC_Convert_Pos = 0;
	EADC->CTL =  (EADC->CTL & EADC_CTL_ADC01CHSEL_MSK) | gEADC_convert_Seq[gEADC_Convert_Pos];

	EADC->CTL &= ~EADC_CTL_ADC0HWTRGEN_Msk;  //硬件触发禁止
	
    // Begin to do EADC conversion.
    EADC_CLR_INT_FLAG(EADC, EADC_STATUS_ADC0F_Msk);
    //ADC中断开启
    EADC_ENABLE_INT(EADC,EADC_CTL_ADC0IEN_Msk);

    NVIC_EnableIRQ(EADC0_IRQn);
    NVIC_SetPriority(EADC0_IRQn,1);	//最高优先级
}



